package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.exception.BusinessException;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.constant.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.constant.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MRS
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        Optional.ofNullable(records).<BusinessException>orElseThrow(()->{throw new BusinessException("系统错误！");});

        // 查询用户
        records.forEach((blog)->{
            //设置blog中的user相关属性
            setUserInfo4Blog(blog);
            //查询是否点过赞，并设置点赞状态
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result getBlogDetailById(Long id) {
        // 根据 id 查询 Blog
        Blog blog = this.getById(id);
        Optional.ofNullable(blog).<BusinessException>orElseThrow(()->{throw new BusinessException("笔记详情为空！");});
        // 设置 Blog 中用户相关的属性值
        this.setUserInfo4Blog(blog);
        // 判断当前登录用户是否点赞过文章
        this.isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 判断当前登录用户是否点赞过文章
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        String key = BLOG_LIKED_KEY + blog.getId();
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //没有登录用户，无需判断是否点赞过
            return ;
        }
        Double isMember = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        blog.setIsLike(isMember != null);

    }


    /**
     * 点赞文章
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {

        String key = BLOG_LIKED_KEY + id;

        //1. 获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2. 判断当前用户是否已经点赞过 set【set数据类型 sismember】
        Double isMember = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        boolean isSuccess = false;
        if (isMember == null) {
            //3. 未点赞，则允许点赞
            //3.1 数据库blog表like点赞数+1
            // 修改点赞数量
            isSuccess = this.update()
                    .setSql("liked = liked + 1").eq("id", id).update();
            if (BooleanUtil.isTrue(isSuccess)) {
                //3.2 数据库更新点赞数成功，点赞过的userId添加到set【set数据类型， sadd】
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4. 已点赞，取消点赞
            //4.1 更新数据库like点赞数-1
            isSuccess = this.update()
                    .setSql("liked = liked - 1").eq("id", id).update();
            if (BooleanUtil.isTrue(isSuccess)) {
                //4.2 redis的set集合中移除userId
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }

        }

        return Result.ok();
    }


    @Override
    public Result getTopFiveUserLikedBlog(Long id) {

        String key = BLOG_LIKED_KEY + id;
        //从zset中获取按时间排序的top5用户 zrange key 0 4
        Set<String> topFive  = stringRedisTemplate.opsForZSet().range(key, 0, 4);

        if (CollectionUtil.isEmpty(topFive)) {
            return Result.ok(Collections.emptyList());
        }
        //从zset获取userId列表，并查出相应用户信息 并封装成UserDto过滤掉敏感信息
        List<UserDTO> userDTOList = topFive.stream().map((userId) -> {
            long uId = Long.parseLong(userId);
            User user = userService.getById(uId);
            //并封装成UserDto过滤掉敏感信息
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).collect(Collectors.toList());


        return Result.ok(userDTOList);
    }

    /**
     * 保存探店笔记
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店博文
        this.save(blog);

        //3.发布探店博文后，推送给关注此用户的所有粉丝
        //3.1 查询关注此用户的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> followList = followService.query().eq("follow_user_id", user.getId()).list();
        long timeMillis = System.currentTimeMillis();
        //3.2 把发布的笔记推送给所有粉丝
        followList.forEach(follow -> {
            //获取粉丝id
            Long userId = follow.getUserId();
            String key = FEED_KEY + userId;
            //给每个粉丝收件箱推送一份
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), timeMillis);

        });

        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询关注好友的探店笔记
     * @param max 上次得分最小时间戳
     * @param offset 偏移量
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = FEED_KEY + userId;
        //查询用户收件箱根据时间顺序降序排序拿到最新时间的笔记 zrevrrangebyscore  key max min WITHSCORES limit offset count
        //每页获取2条关注博主的最新探店笔记
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //redis收件箱中没有
        if (typedTuples.isEmpty() || typedTuples == null) {
            return Result.ok();
        }

        //计算minTime、offset返回并把blog列表返回
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;//此次查询最小的得分【因为是降序】
        int os = 1;//偏移量offset【上次查询结果中，与最小值得分相同的元素个数】 默认为1因为zset必定有一个元素
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {//5 4 4 2 2
            //blogId列表
            blogIds.add(Long.valueOf(typedTuple.getValue()));
            //获取得分(时间戳)
            long time = typedTuple.getScore().longValue();

            //计算与上次查询结果得分最小值相同的的元素个数【因为下一次的滚动分页查询记录了上一次的得分最小值开始的】
            if (time == minTime) {
                os++;
            } else {
                //因为是按时间戳降序，所以最后一次遍历的就是最小的得分
                minTime = time;
                //重置计数器
                os = 1;
            }
        }
        String join = StrUtil.join(",", blogIds);
        List<Blog> blogList = this.lambdaQuery()
                .in(Blog::getId, blogIds)
                .last("ORDER BY FIELD(id, " + join + ")")
                .list();

        for (Blog blog : blogList) {
            // 设置 Blog 中用户相关的属性值
            this.setUserInfo4Blog(blog);
            // 判断当前登录用户是否点赞过文章
            this.isBlogLiked(blog);
        }

        // 4.封装为 ScrollResult 并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);

        return Result.ok(scrollResult);
    }

    private void setUserInfo4Blog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
